package com.rongshu.view.userInfo.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.penpal.activity.PostDetailsActivity;
import com.rongshu.view.penpal.bean.PenpalArticleResponse;
import com.rongshu.view.userInfo.adapter.InvitationAdapter;
import com.rongshu.view.userInfo.iview.InvitationView;
import com.rongshu.view.userInfo.presenter.InvitationPresenter;
import com.rongshu.widget.BanyanDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class InvitationActivity extends BaseActivity<InvitationPresenter> implements InvitationView, InvitationAdapter.OnItemFunctionClickListener {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;
    @BindView(R.id.empty_hint)
    TextView emptyHint;

    //manager
    private LinearLayoutManager manager = null;
    //adapter
    private InvitationAdapter adapter = null;
    //map
    private Map<String, Object> map = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    //refresh,load
    private boolean isrefresh = true;
    //dialog 删除帖子用
    private BanyanDialog banyanDialog = null;
    //position
    private int position = 0;
    //request
    private final int REQUEST = 0x01;

    @Override
    protected int initLayout() {
        return R.layout.activity_invitation_view;
    }

    @Override
    protected void initView() {
        //set presenter
        setPresenter(new InvitationPresenter(this), this);
        txt_top_title.setText(R.string.my_invitation);
        //layoutmanager
        manager = new LinearLayoutManager(this);
        //adapter
        adapter = new InvitationAdapter(this);
        adapter.setOnItemFunctionClickListener(this);
        //recyclerview
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);
        //触发自动刷新
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                isrefresh = true;
                pageIndex = 1;
                refreshLayout.resetNoMoreData();
                getMyForum();
                refreshlayout.finishRefresh(2000, false);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isrefresh = false;
                pageIndex++;
                getMyForum();
                refreshlayout.finishLoadmore(2000, false);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    /**
     * 我的帖子
     */
    public void getMyForum() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("page", pageIndex);
        map.put("pagesize", pageSize);
        presenter.getMyForum(user_id,
                pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 帖子删除
     *
     * @param penpalwill_id
     * @param topic_id
     */
    public void deletePenpalArticle(int penpalwill_id, int topic_id) {
        //user_id
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("topic_id", topic_id);
        map.put("penpalwill_id", penpalwill_id);
        presenter.deletePenpalArticle(user_id,
                topic_id, penpalwill_id, Common.encryptionSign(map));
        map.clear();
    }

    @OnClick({R.id.layout_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST://点赞，评论数更新
                    int likeCount = data.getIntExtra(Constant.LIKE_COUNT, 0);
                    int commentCount = data.getIntExtra(Constant.COMMENT_COUNT, 0);
                    List<PenpalArticleResponse.ResponseBean> beans = adapter.getInvitations();
                    beans.get(position).setLikeCount(likeCount);
                    beans.get(position).setCommentCount(commentCount);
                    adapter.notifyItemChanged(position);
                    break;
            }
        }
    }

    /**
     * 登录提示dialog
     */
    public void showInvitationDeleteHint(final int penpalwill_id, final int topic_id) {
        //dialog
        BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
        builder.setTitle("提示");
        builder.setContent("确定要删除帖子嘛");
        builder.setLeft("取消");
        builder.setRight("确定");
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                banyanDialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                banyanDialog.dismiss();
                deletePenpalArticle(penpalwill_id, topic_id);
            }
        });
        banyanDialog = builder.create();
        banyanDialog.show();
    }

    @Override
    public void onClick(int position) {
        this.position = position;
        PenpalArticleResponse.ResponseBean responseBean = adapter.getInvitations().get(position);
        Intent intent = new Intent(this, PostDetailsActivity.class);
        intent.putExtra(Constant.POST_ID, responseBean.getTopic_id());
        intent.putExtra("showJoinIcon", true);
        startActivityForResult(intent, REQUEST);
    }

    @Override
    public void onDeleteClick(int position) {
        this.position = position;
        PenpalArticleResponse.ResponseBean responseBean = adapter.getInvitations().get(position);
        showInvitationDeleteHint(responseBean.getPenpalwill_id(), responseBean.getTopic_id());
    }

    /**
     * 我的帖子回调
     */
    @Override
    public void onInvitation(PenpalArticleResponse invitation) {
        if (invitation.getErrCode() == 0) {
            List<PenpalArticleResponse.ResponseBean> list = invitation.getResponse();
            if (adapter != null) {
                if (isrefresh) {
                    refreshLayout.finishRefresh();
                    if (list == null || list.isEmpty()) {
                        refreshLayout.setVisibility(View.GONE);
                        layout_empty.setVisibility(View.VISIBLE);
                    } else {
                        refreshLayout.setVisibility(View.VISIBLE);
                        layout_empty.setVisibility(View.GONE);
                        adapter.setInvitations(list);
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    if (list == null || list.isEmpty()) {
                        refreshLayout.finishLoadmoreWithNoMoreData();
                    } else {
                        refreshLayout.finishLoadmore();
                        adapter.addInvitations(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    /**
     * 帖子删除
     *
     * @param bean
     */
    @Override
    public void onDeletePenpalArticle(INetBean bean) {
        if (bean.getErrCode() == 0) {
            adapter.getInvitations().remove(position);
            adapter.notifyDataSetChanged();
        } else {
            toast(bean.getErrMsg());
        }
    }
}
